using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DotNetSide.SqlScriptGenerator.Properties;
using System.Security.Permissions;
using Microsoft.Win32;
using System.Reflection;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;

[assembly: SecurityPermission(SecurityAction.RequestMinimum)]
[assembly: RegistryPermissionAttribute(SecurityAction.RequestMinimum, ViewAndModify = "HKEY_LOCAL_MACHINE")]

namespace DotNetSide.SqlScriptGenerator
{
    public partial class SettingsWindow : Form
    {
        public SettingsWindow()
        {
            InitializeComponent();
        }

        private void SettingsWindow_Load(object sender, EventArgs e)
        {
            this.SSMSIntegrationCheckBox.Checked = Settings.Default.SSMSIntegration;
        }

        private void OKButton_Click(object sender, EventArgs e)
        {
            if (this.SSMSIntegrationCheckBox.Checked != Settings.Default.SSMSIntegration)
            {
                if (this.SSMSIntegrationCheckBox.Checked)
                {
                    RegSSG();
                }
                else
                {
                    UnRegSSG();
                }
                Settings.Default.SSMSIntegration = this.SSMSIntegrationCheckBox.Checked;
                Settings.Default.Save();
            }
            this.Close();
        }

        private void RegSSG()
        {
            try
            {
                string fx = Path.Combine(CLRInfos.SystemDirectory(), "regasm.exe");
                string path = Path.Combine(Application.StartupPath, Constants.SSGManagementAsm);

                ProcessStartInfo info = new ProcessStartInfo(fx);
                info.CreateNoWindow = false;
                info.WindowStyle = ProcessWindowStyle.Hidden;
                info.Arguments = "/codebase \"" + path + "\"";
                Process.Start(info);

                info.Arguments = "/tlb \"" + path + "\"";
                Process.Start(info);

                RegistryKey key = Registry.LocalMachine.OpenSubKey(Constants.SSMSAddinRegistryPath, true);
                RegistryKey ssgKey = key.CreateSubKey(Constants.SSGConnect);
                ssgKey.SetValue("LoadBehavior", 1, RegistryValueKind.DWord);
                ssgKey.SetValue("Description", "SqlScriptGenerator", RegistryValueKind.String);
                ssgKey.SetValue("FriendlyName", "Sql Script Generator addin, SQL Server Management Studio Extension", RegistryValueKind.String);
                ssgKey.Close();
                key.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void UnRegSSG()
        {
            try
            {
                string fx = Path.Combine(CLRInfos.SystemDirectory(), "regasm.exe");
                string path = Path.Combine(Application.StartupPath, Constants.SSGManagementAsm);

                ProcessStartInfo info = new ProcessStartInfo(fx, "/unregister " + path);
                info.CreateNoWindow = false;
                info.WindowStyle = ProcessWindowStyle.Hidden;
                Process.Start(info);

                RegistryKey key = Registry.LocalMachine.OpenSubKey(Constants.SSMSAddinRegistryPath, true);
                key.DeleteSubKey(Constants.SSGConnect);
                key.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
       }
    }

    //
    // Thanks to Corrado Cavalli
    //
    public class CLRInfos
    {
        //API declares
        [DllImport("mscoree.dll")]
        static extern Int32 GetCORSystemDirectory([MarshalAs(UnmanagedType.LPWStr)] System.Text.StringBuilder buffer, Int32 buflen, ref Int32 numbytes);
        [DllImport("mscoree.dll")]
        static extern Int32 GetCORVersion([MarshalAs(UnmanagedType.LPWStr)] System.Text.StringBuilder buffer, Int32 buflen, ref Int32 numbytes);
        static public String SystemDirectory()
        {
            System.Text.StringBuilder buf = new System.Text.StringBuilder(1024);
            Int32 iBytes = 0;
            Int32 ret = GetCORSystemDirectory(buf, buf.Capacity, ref iBytes);
            return buf.ToString().Substring(0, iBytes - 1);
        }
        public static string Version()
        {
            System.Text.StringBuilder buf = new System.Text.StringBuilder(1024);
            Int32 iBytes = 0;
            Int32 ret = GetCORVersion(buf, buf.Capacity, ref iBytes);
            return buf.ToString().Substring(0, iBytes - 1);
        }
    }
}